package com.iteaj.iboot.module.iot.controller;

import java.util.List;
import java.util.stream.Collectors;

import com.dtflys.forest.annotation.Post;
import com.iteaj.framework.result.Result;
import com.iteaj.framework.security.Logical;
import com.iteaj.iboot.module.iot.collect.messageParsing.analyticRule;
import com.iteaj.iboot.module.iot.collect.messageParsing.modbus.ModbusCommandHelper;
import com.iteaj.iboot.module.iot.collect.messageParsing.modbus.ModbusRtuHelper;
import com.iteaj.iboot.module.iot.dto.SignalOfModelDto;
import com.iteaj.iboot.module.iot.entity.Signal;
import com.iteaj.iboot.module.iot.mapper.AnalyticRuleMapper;
import com.iteaj.iboot.module.iot.service.IAnalyticRuleService;
import com.iteaj.iboot.module.iot.service.ISignalService;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.springframework.web.bind.annotation.*;
import com.iteaj.framework.security.CheckPermission;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.iteaj.framework.BaseController;

/**
 * 寄存器点位管理
 *
 * @author iteaj
 * @since 2022-07-22
 */
@RestController
@RequestMapping("/iot/signal")
public class SignalController extends BaseController {

    private final ISignalService signalService;

    private final IAnalyticRuleService iAnalyticRuleService;

    private final AnalyticRuleMapper analyticRuleMapper;
    public SignalController(ISignalService signalService,
                            IAnalyticRuleService iAnalyticRuleService,
                            AnalyticRuleMapper analyticRuleMapper) {
        this.signalService = signalService;
        this.iAnalyticRuleService=iAnalyticRuleService;
        this.analyticRuleMapper=analyticRuleMapper;
    }

    /**
    * 列表查询
    * @param page 分页
    * @param entity 搜索条件
    */
    @GetMapping("/view")
    @CheckPermission({"iot:signal:view"})
    public Result<IPage<Signal>> list(Page<Signal> page, Signal entity) {
        return this.signalService.detailByPage(page, entity);
    }

    /**
     * 获取指定型号下面的点位列表
     * @param modelId 型号id
     */
    @GetMapping("/listByModel")
    public Result<List<SignalOfModelDto>> listByModel(Integer modelId) {
        List<SignalOfModelDto> modelDtos = this.signalService.list(new Signal(modelId))
                .stream().map(item -> new SignalOfModelDto().setId(item.getId().toString())
                .setName(item.getName()).setAddress(item.getRegistersAddress())
                .setFieldName(item.getFieldName())).collect(Collectors.toList());
        return success(modelDtos);
    }

    /**
    * 获取编辑记录
    * @param id 记录id
    */
    @GetMapping("/edit")
    @CheckPermission({"iot:signal:edit"})
    public Result<Signal> getById(Long id) {
        return this.signalService.getById(id);
    }

    /**
    * 新增或者更新记录
    * @param entity
    */
    @PostMapping("/saveOrUpdate")
    @CheckPermission(value = {"iot:signal:edit", "iot:signal:add"}, logical = Logical.OR)
    public Result<Boolean> save(@RequestBody Signal entity) {
        //创建问询帧报文
        int commFunction = entity.getCommFunction();
        int deviceStation = entity.getDeviceStation();
        String registersAddress = entity.getRegistersAddress();
        int registersCount = entity.getRegistersCount();
        byte[] inquiryFrame;
        switch (commFunction){
            case 1:
                inquiryFrame = ModbusCommandHelper.createFunction01(deviceStation, Integer.parseInt(registersAddress),registersCount);
                break;
            case 2:
                inquiryFrame = ModbusCommandHelper.createFunction02(deviceStation, Integer.parseInt(registersAddress),registersCount);
                break;
            case 3:
                inquiryFrame = ModbusCommandHelper.createFunction03(deviceStation, Integer.parseInt(registersAddress),registersCount);
                break;
            case 4:
                inquiryFrame = ModbusCommandHelper.createFunction04(deviceStation, Integer.parseInt(registersAddress),registersCount);
                break;
            case 5:
                inquiryFrame = ModbusCommandHelper.createFunction05(deviceStation, Integer.parseInt(registersAddress),true);
                break;
            case 6:
                inquiryFrame = ModbusCommandHelper.createFunction06(deviceStation, Integer.parseInt(registersAddress),(short) 0);
                break;
            default:
                inquiryFrame = ModbusCommandHelper.createFunction03(deviceStation, Integer.parseInt(registersAddress),registersCount);
        }
        String message = new String(inquiryFrame);
        int crc = ModbusRtuHelper.calculateCRC(message+"0000", 0, 16);
        entity.setMessage(message+Integer.toHexString(crc));
        return this.signalService.saveOrUpdate(entity);
    }


    /**
    * 删除指定记录
    * @param idList
    */
    @PostMapping("/del")
    @CheckPermission({"iot:signal:del"})
    public Result<Boolean> remove(@RequestBody List<Long> idList) {

        return this.signalService.removeByIds(idList);
    }

    /**
     * 查看所有的规则（网关）
     * @return
     */
    @GetMapping("/getSignal")
    public Result<Signal> getSignal() {
        return this.analyticRuleMapper.getAll();
    }
}

